package cn.chousensei.chousenseiblog.service.impl;

import cn.chousensei.chousenseiblog.dao.BlogMapper;
import cn.chousensei.chousenseiblog.dao.UserMapper;
import cn.chousensei.chousenseiblog.dto.BlogDTO;
import cn.chousensei.chousenseiblog.dto.PaginationDTO;
import cn.chousensei.chousenseiblog.model.Blog;
import cn.chousensei.chousenseiblog.service.BlogService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class BlogServiceImpl implements BlogService {

    @Autowired
    BlogMapper blogMapper;

    @Autowired
    UserMapper userMapper;

    @Override
    public PaginationDTO list(Integer page, Integer size) {
        PaginationDTO<BlogDTO> paginationDTO = new PaginationDTO<>();
        Integer totalCount = blogMapper.count();
        Integer totalPage;

        if (totalCount % size == 0) {
            totalPage = totalCount / size;
        } else {
            totalPage = totalCount / size + 1;
        }

        if (page < 1) {
            page = 1;
        }
        if (page > totalPage) {
            page = totalPage;
        }
        paginationDTO.setPagination(totalPage, page);

        Integer offset = size * (page - 1);
        List<Blog> blogs = blogMapper.selectPageOrderByCreateTime(offset, size);
        List<BlogDTO> blogDTOS = blogs.stream().map(blog -> {
            BlogDTO blogDTO = new BlogDTO();
            BeanUtils.copyProperties(blog, blogDTO);
            blogDTO.setUser(userMapper.findByUserId(blog.getCreator()));
            return blogDTO;
        }).collect(Collectors.toList());

        paginationDTO.setData(blogDTOS);

        return paginationDTO;
    }

    @Override
    public void createOrUpdate(Blog blog) throws Exception {
        if (blog.getId() == null) {
            blog.setViewCount(0L);
            blog.setCommentCount(0L);
            blog.setLikeCount(0L);
            blog.setGmtCreate(System.currentTimeMillis());
            blog.setGmtModified(blog.getGmtCreate());

            blogMapper.insert(blog);
        } else {
            blog.setGmtModified(System.currentTimeMillis());
            int updated = blogMapper.updateSelective(blog);
            if (updated != 1) {
                throw new Exception();
            }
        }
    }
}
